<!DOCTYPE html>
<html>
<head>
    <title>不敗君 www.bubaijun.com</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="__STATIC__/libs/layui/css/layui.css">
    <script type="text/javascript" src="__STATIC__/libs/jquery/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="__STATIC__/libs/layui/layui.js"></script>
    <style>
        layui-card-header {
            border-color: #EEEEEE;
        }

        .layui-form {
            margin-top: 30px;
            padding: 20px;
            background-color: #F9F9F9;
        }

        .layui-form-label {
            width: 100px;
        }

        .layui-input-block {
            margin-left: 130px;
        }

        .attr-key-item, #sku-table {
            background: #F9F9F9;
            padding: 20px;
        }

        .attr-key-item {
            padding-bottom: 0;
        }

        #sku-table table {
            width: 100%;
        }

        .attr-key-item .sku-title {
            margin-bottom: 10px
        }

        .attr-key-item .sku-title input {
            display: inline;
            width: 260px;
            margin-right: 10px;
        }

        .attr-vals {
            width: 100%;
            display: block;
        }

        .btn-remove-attr-key, .btn-add-attr-val, .btn-remove-attr-val {
            color: #0071F2;
        }

        #images .layui-input-inline {
            width: auto;
            margin-bottom: 10px;
        }

        .static-bottom {
            background: white;
            bottom: 0px;
            padding-bottom: 40px;
            left: 0;
            right: 0;
            padding-top: 20px;
            border-top: 1px solid #cccccc;
            text-align: center;
        }

        .static-bottom .layui-input-block {
            margin-left: 0;
        }
    </style>
</head>

<body>
<form class="layui-form" action="" id="myForm" method="post" style="">
    <input type="hidden" id="product_id" name="product_id" value="{$id}">
    <input type="hidden" id="count" value="{$count}">

    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">

                    <div class="layui-form-item">
                        <label class="layui-form-label">商品規格</label>
                        <div class="layui-input-inline">
                            <button type="button" class="layui-btn layui-btn-primary btn-add-attr-key">
                                添加自定義商品規格
                            </button>
                        </div>
                    </div>

                    <!-- 放多規格 -->
                    <div id="sku-container">
                        {if condition="count($spec) gt 0"}
                        {volist name="spec" id="vo"}
                        <div class="layui-form-item attr-key-item">
                            <div class="sku-title">
                                <input lay-verify="required" type="text" value="{$vo.name}"
                                       name="attr_key[{$vo.id}]" placeholder="規格名稱，例如：顏色，尺寸"
                                       class="layui-input attr-key">
                                <a class="btn-remove-attr-key" href="javascript:void(0);">刪除</a></div>
                            <div class="attr-vals">
                                {volist name="vo.items" id="vo1" key="k"}
                                <div class="layui-inline">
                                    <div class="layui-input-inline"><input value="{$vo1}"
                                            attr_val_id="{$k}"
                                            attr_key_id="{$vo.id}" type="text"
                                            name="attr_val[{$vo.id}][{$k}]"
                                            placeholder="例如：白色" lay-verify="required" class="attr-val layui-input">
                                    </div>
                                    <div class="layui-form-mid layui-word-aux"><a class="btn-remove-attr-val" href="javascript:void(0);">刪除</a>
                                    </div>
                                </div>
                                {/volist}
                            </div>
                            <div class="layui-inline">
                                <div class="layui-form-mid layui-word-aux">
                                    <a class="btn-add-attr-val" href="javascript:void(0);" attr_key_id="{$vo.id}">添加自定義項</a>
                                </div>
                            </div>
                        </div>
                        {/volist}
                        {/if}
                    </div>

                    <!-- SKU表 -->
                    <div class="layui-form-item" id="sku-table"></div>
                </div>
            </div>
        </div>
    </div>


    <div class="layui-form-item static-bottom">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit="myForm" lay-filter="myForm">立即提交</button>
            <button class="layui-btn layui-btn-normal" type="button" onclick="javascript:history.back(-1);">返回
            </button>
        </div>
    </div>
</form>

<script type="text/javascript">
    // layui 公共配置
    const layconfig = {
        base: 'layui/js/',
        version: true,
        debug: true,
    };
</script>
<script type="text/javascript">
    const init = function (options) {
        var _modules = options.modules || [];
        _modules = _modules.concat('layer', 'form', 'element');

        layui.config(layconfig).use(_modules, function (opt) {

            var form = layui.form,
                laytpl = layui.laytpl,
                element = layui.element;

            // 其他事件
            if (options.exec) {
                options.exec(layui);
            }

            form.render();
        });
    };
</script>

<script type="text/javascript">
    $(function () {
        var opt = {
            modules: ['table', 'form', 'element', 'laytpl', 'tree'],
            exec: function (layui) {

                // -- 商品規格開始 --

                // 添加自定義 attr key
                var already_set_sku_vals = {};      // 已經設置的SKU值數據
                var arr_sku = {};                   // 已經設置的SKU值數據
                var attr_key_id = '';               // 自定義 attr key id
                var attr_key_sort = 0;              // 自定義 attr key sort
                var attr_val_id = '';               // 自定義 attr val id
                var attr_val_sort = 0;              // 自定義 attr val sort

                var count = $('#count').val();
                if (count > 0) {
                    initSkuTable();
                }

                $(document).on("click", ".btn-add-attr-key", function () {
                    var tpl_attr_key_model = $("#tpl-attr-key-model").html();
                    attr_key_id = uuid(32, 16);
                    attr_val_id = uuid(32, 16);
                    attr_key_sort++;
                    var data = {attr_key_id: attr_key_id, attr_val_id: attr_val_id, attr_key_sort: attr_key_sort};
                    layui.laytpl(tpl_attr_key_model).render(data, (html) => {
                        $("#sku-container").append(html);   // 添加到該按鈕的前面
                        layui.form.render('checkbox');
                        initSkuTable();
                    });
                });

                // 刪除自定義 attr key
                $(document).on("click", ".btn-remove-attr-key", function () {
                    $(this).parent().parent().remove(); // 添加到該按鈕的前面
                    initSkuTable();
                });

                // 監聽 attr key 輸入
                $(document).on("change", ".attr-key", function () {
                    var current_val = $(this).val();
                    // 判斷標題是否已經重複了
                    var appear_time = 0;
                    $(".attr-key").each(function () {
                        var val = $(this).val();
                        if (current_val == val) {
                            appear_time++;
                        }
                    });

                    if (appear_time > 1) {
                        layer.msg('該規格名稱已經存在!', {time: 1000});
                        $(this).val("");
                        return;
                    }
                    initSkuTable();
                });

                // 監聽attr val 輸入
                $(document).on("change", ".attr-val", function () {
                    var current_val = $(this).val();
                    // 判斷值是否已經重複了
                    var appear_time = 0;
                    $(".attr-val").each(function () {
                        var val = $(this).val();
                        if (current_val == val) {
                            appear_time++;
                        }
                    });
                    if (appear_time > 1) {
                        layer.msg('該規格值已經存在!', {time: 1000});
                        $(this).val("");
                        return;
                    }
                    initSkuTable();
                });

                // 監聽attr_val 輸入
                layui.form.on('checkbox(attr-val)', function (data) {
                    initSkuTable();
                });

                // 繪製表格
                function initSkuTable() {
                    get_already_set_sku_vals();     // 獲取已經設置的SKU值
                    var attrs = [];                // 存放屬性數組
                    var total_row = 1;              // 總行數
                    var sku_table_dom = "";         // sku表格dom

                    // 獲取元素類型
                    $(".attr-key-item").each(function (index, item) {
                        var attr_key = {};
                        attr_key.attr_key = $(item).find(".attr-key").val();

                        var attr_vals = [];
                        $(item).find('.attr-val').each(function (index, item) {

                            var val = $(item).val();
                            if (val == undefined || val == "") {
                                return;
                            }
                            var attr_val = {};  // attr val對象
                            attr_val.attr_key_id = $(this).attr("attr_key_id");
                            attr_val.attr_val_id = $(this).attr("attr_val_id");
                            attr_val.attr_val = val;
                            attr_vals.push(attr_val);
                        });

                        if (attr_vals && attr_vals.length > 0) {
                            total_row = total_row * attr_vals.length;
                            attr_key.attr_vals = attr_vals;         // sku值數組
                            attrs.push(attr_key);                   // 保存進數組中
                        }
                    });

                    sku_table_dom = "<table class='layui-table skuTable'><thead><tr>";
                    // 創建表頭
                    for (var i = 0; i < attrs.length; i++) {
                        sku_table_dom += '<th>' + attrs[i].attr_key + '</th>';
                    }
                    sku_table_dom += '<th>價格</th><th>庫存</th>';
                    sku_table_dom += "</thead></tr>";

                    // 循環處理表體
                    for (var i = 0; i < total_row; i++) { //總共需要創建多少行
                        var curr_row_doms = "";
                        var row_count = 1;      // 記錄行數
                        var attr_key_ids = [];  // 記錄 attr key id
                        var attr_val_ids = [];  // 記錄 attr val id
                        var attr_key_arr = [];  // 記錄 attr key
                        var attr_val_arr = [];  // 記錄 attr val

                        for (var j = 0; j < attrs.length; j++) {
                            var attr_vals = attrs[j].attr_vals;                   // attr val 數組
                            var attr_vals_len = attr_vals.length;                 // attr val 長度
                            row_count = (row_count * attr_vals_len);              // 目前的生成的總行數
                            var an_inter_bank_num = (total_row / row_count);      // 跨行數
                            var point = ((i / an_inter_bank_num) % attr_vals_len);
                            attr_key_arr.push(attrs[j].attr_key);
                            if (0 == (i % an_inter_bank_num)) {
                                // 需要創建td
                                curr_row_doms += '<td rowspan=' + an_inter_bank_num + '>' + attr_vals[point].attr_val + '</td>';
                                attr_val_arr.push(attr_vals[point].attr_val);
                                attr_val_ids.push(attr_vals[point].attr_val_id);
                                attr_key_ids.push(attr_vals[point].attr_key_id);
                            } else {
                                // 當前單元格為跨行
                                attr_val_arr.push(attr_vals[parseInt(point)].attr_val);
                                attr_val_ids.push(attr_vals[parseInt(point)].attr_val_id);
                                attr_key_ids.push(attr_vals[parseInt(point)].attr_key_id);
                            }
                        }

                        var str_val_ids = attr_val_ids.toString()
                        var already_set_sku_price = ""; // 已經設置的SKU價格
                        var already_set_sku_stock = ""; // 已經設置的SKU庫存

                        if (already_set_sku_vals) {
                            var curr_group_sku_val = already_set_sku_vals[str_val_ids];//當前這組SKU值
                            if (curr_group_sku_val) {
                                already_set_sku_price = curr_group_sku_val.sku_price;
                                already_set_sku_stock = curr_group_sku_val.sku_stock;
                            }
                        }

                        sku_table_dom += '<tr attr_val_ids="' + attr_val_ids + '" attr_key_ids="' + attr_key_ids.toString() + '" attr_val_names="' + attr_val_arr.join(";") + '"  propnames="' + attr_key_arr.join(";") + '" class="sku_table_tr">' + curr_row_doms +
                            '<td><input type="number" step="0.01" min="0.01" name="sku_price" class="layui-input" value="' + already_set_sku_price + '"/></td>' +
                            '<td><input type="number" step="1" min="0" name="sku_stock" class="layui-input" value="' + already_set_sku_stock + '"/></td>' +
                            '</tr>';
                    }
                    $("#sku-table").html(sku_table_dom);
                    get_already_set_sku_vals();
                    layui.form.render("checkbox");
                }

                // 單擊添加 attr val
                $(document).on("click", ".btn-add-attr-val", function () {
                    var tpl_attr_val_model = $("#tpl-attr-val-model").html();
                    attr_val_sort++;
                    attr_val_id = uuid(32, 16);
                    attr_key_id = $(this).attr('attr_key_id');
                    var data = {attr_key_id: attr_key_id, attr_val_id: attr_val_id, attr_val_sort: attr_val_sort};
                    layui.laytpl(tpl_attr_val_model).render(data, (html) => {
                        $(this).parent().parent().parent().find(".attr-vals").append(html); // 添加到該按鈕的前面
                        layui.form.render('checkbox');
                    });
                    initSkuTable();
                });

                // 單擊刪除 attr val
                $(document).on("click", ".btn-remove-attr-val", function () {
                    $(this).parent().parent().remove(); // 添加到該按鈕的前面
                    initSkuTable();
                });

                function get_already_set_sku_vals() {
                    console.log(count)
                    already_set_sku_vals = {};
                    arr_sku = {};
                    //獲取設置的SKU屬性值
                    $("tr.sku_table_tr").each(function () {
                        var sku_price = $(this).find("input[name=sku_price]").val();    // SKU價格
                        var sku_stock = $(this).find("input[name=sku_stock]").val();    // SKU庫存
                        if (sku_price || sku_stock) {
                            // 已經設置了全部或部分值
                            var attr_val_ids = $(this).attr("attr_val_ids");    // SKU值id集合
                            // var attr_val_names = $(this).attr("attr_val_names");//SKU值name集合
                            already_set_sku_vals[attr_val_ids] = {
                                "sku_price": sku_price,
                                "sku_stock": sku_stock,
                            };
                            arr_sku[attr_val_ids] = {
                                "sku_price": sku_price,
                                "sku_stock": sku_stock,
                            }
                        }
                    });
                }

                layui.form.on('checkbox(unify-price)', function (data) {
                    var unify_price = $("input[name=unify_price]").val();
                    if (data.elem.checked) {
                        $("input[name=sku_price]").val(unify_price);
                    }
                    get_already_set_sku_vals();
                });

                layui.form.on('checkbox(unify-stock)', function (data) {
                    var unify_stock = $("input[name=unify_stock]").val();
                    if (data.elem.checked) {
                        $("input[name=sku_stock]").val(unify_stock);
                    }
                });

                function uuid(len, radix) {
                    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
                    var uuid = [], i;
                    radix = radix || chars.length;

                    if (len) {
                        // Compact form
                        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
                    } else {
                        // rfc4122, version 4 form
                        var r;

                        // rfc4122 requires these characters
                        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                        uuid[14] = '4';

                        // Fill in random data.  At i==19 set the high bits of clock sequence as
                        // per rfc4122, sec. 4.1.5
                        for (i = 0; i < 36; i++) {
                            if (!uuid[i]) {
                                r = 0 | Math.random() * 16;
                                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                            }
                        }
                    }

                    return uuid.join('');
                }

                // -- 商品規格結束 --

                layui.form.on('submit(myForm)', function () {
                    var product_id = $('#product_id').val();
                    get_already_set_sku_vals();
                    var data = $('#myForm').serialize() + "&sku=" + JSON.stringify(arr_sku) + "&id=" + product_id;

                    $.ajax({
                        url: '{:url("product/spec")}',
                        method: 'POST',
                        data: data,
                        success: function (res) {
                            layer.msg(res.msg);
                            if (res.code === 1) {
                                setTimeout(function () {
                                    window.location.href = res.data;
                                }, 1500)
                            }
                        }
                    });

                    return false;
                });

            }
        };
        init(opt);
    });

</script>
<!-- 自定義商品規格key -->
<script type="text/html" id="tpl-attr-key-model">
    <div class="layui-form-item attr-key-item">
        <div class="sku-title">
            <input lay-verify="required" type="text" name="attr_key[{{d.attr_key_id}}]" placeholder="規格名稱，例如：顏色，尺寸"
                   class="layui-input attr-key"><a class="btn-remove-attr-key" href="javascript:void(0);">刪除</a>
        </div>
        <div class="attr-vals">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <input attr_val_id="{{d.attr_val_id}}" attr_key_id="{{d.attr_key_id}}" type="text"
                           name="attr_val[{{d.attr_key_id}}][{{d.attr_val_id}}]" placeholder="例如：白色"
                           lay-verify="required" class="attr-val layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">
                    <a class="btn-remove-attr-val" href="javascript:void(0);">刪除</a>
                </div>
            </div>
        </div>

        <div class="layui-inline">
            <div class="layui-form-mid layui-word-aux">
                <a class="btn-add-attr-val" href="javascript:void(0);" attr_key_id="{{d.attr_key_id}}">添加自定義項</a>
            </div>
        </div>
    </div>
</script>
<script type="text/html" id="tpl-attr-val-model">
    <div class="layui-inline attr-vals-item">
        <div class="layui-input-inline">
            <input attr_val_id="{{d.attr_val_id}}" attr_key_id="{{d.attr_key_id}}" type="text"
                   name="attr_val[{{d.attr_key_id}}][{{d.attr_val_id}}]" class="attr-val layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">
            <a class="btn-remove-attr-val" href="javascript:void(0);">刪除</a>
        </div>
    </div>
</script>

</body>
</html>